#include "EyerWASMEventXMLHttpRequest.hpp"

#include <emscripten.h>
#include <stdio.h>

extern "C"
{
EMSCRIPTEN_KEEPALIVE int EyerWASMEvent_XMLHttpRequest_Send(void * ctx, const char * url);

EMSCRIPTEN_KEEPALIVE int EyerWASMEvent_XMLHttpRequest_Send_On_DONE(void * ctx, int httpStatus, uint8_t * data, int len)
{
    Eyer::EyerWASMEventXMLHttpRequest * xmlHttpRequest = (Eyer::EyerWASMEventXMLHttpRequest *)ctx;
    return xmlHttpRequest->EyerWASMEvent_XMLHttpRequest_Send_On_DONE(httpStatus, data, len);
}
}

namespace Eyer
{
    EyerWASMEventXMLHttpRequest::EyerWASMEventXMLHttpRequest(const std::string & _url)
        : url(_url)
    {

    }

    EyerWASMEventXMLHttpRequest::~EyerWASMEventXMLHttpRequest()
    {
        len = 0;
        if(data != nullptr){
            free(data);
            data = nullptr;
        }
    }

    int EyerWASMEventXMLHttpRequest::Run()
    {
        std::unique_lock<std::mutex> lck(mtx);
        EyerWASMEvent_XMLHttpRequest_Send(this, url.c_str());
        return 0;
    }

    int EyerWASMEventXMLHttpRequest::EyerWASMEvent_XMLHttpRequest_Send_On_DONE(int _httpStatus, uint8_t * _data, int _len)
    {
        std::unique_lock<std::mutex> lck(mtx);
        printf("EyerWASMEvent_XMLHttpRequest_Send_On_DONE\n");

        httpStatus = _httpStatus;

        len = _len;
        if(data != nullptr){
            free(data);
            data = nullptr;
        }

        data = (uint8_t *)malloc(len);
        memcpy(data, _data, len);

        isFinished = true;
        cond.notify_all();
        return 0;
    }
}